<template>
  <upload-excel :on-success="handleSuccess" />
</template>

<script>
import UploadExcel from '@/components/UploadExcel'
import { importEmployee } from '@/api/employees'
import { formatTime } from '@/utils/index'
export default {
  name: 'Import',
  components: {
    UploadExcel
  },
  methods: {
    async handleSuccess({ header, results }) {
      console.log(header, results)
      // header中, results中的数据是中文的, 但是提交给后台的要是英文的
      const newArr = this.transExcelHander(results)
      // 调用导入接口
      await importEmployee(newArr) // 调用导入接口
      this.$router.back()
    },
    transExcelHander(results) {
      const userRelations = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber'
      }
      const newArr = results.map(item => {
        const userInfo = {}
        for (const key in item) {
          const newKey = userRelations[key]
          userInfo[newKey] = item[key]
          if (['correctionTime', 'timeOfEntry'].includes(newKey)) {
            // 需要对key对应的value做时间处理
            // 严格来讲需要使用与excel插件配套的时间处理函数 处理成标准的时间Date格式
            // 后端接口才能识别
            userInfo[newKey] = formatTime(item[key])
          }
        }
        return userInfo
      })
      console.log(newArr)
      return newArr
    }
  }
}
</script>
